package com.tjl.thread_pool;

import java.util.concurrent.*;

/*1. 定义一个类，实现Callable接口。此线程可以计算1--100的所有数字的累加和。

2. 定义测试类，和main()方法，使用线程池启动线程，并获取计算结果，并将结果打印到控制台。*/
public class Test {
    public static void main(String[] args) {
        //1.创建线程池
        ExecutorService pool = new ThreadPoolExecutor(
                3,
                5,
                2,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        //2.处理callable任务
        Future future = pool.submit(new task(100));


        //3、执行完Callable任务后，需要获取返回结果。
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


    }


}


class task implements Callable {
    private int n = 0;

    public task(int n) {
        this.n = n;
    }

    @Override
    public Object call() throws Exception {

        int sum =0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return Thread.currentThread().getName()+"求出了1-"+n+"的和是："+sum;
    }
}
